package com.tongtech.space.common.utils.desensitize;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 脱敏函数接口组装类
 *
 * @author jinjiayu
 * @since 2021/4/12
 */
@Data
@Slf4j
public abstract class AbstractDesensitizeWrapper<T,R> {
    private T obj;
    private Map<String, List<DesensitizeFunc<T,R>>> desensitizeFuncMap;
    private static Map<DesensitizeFunc<?, ?>, Field> cache = new ConcurrentHashMap<>();

    /**
     * 动态脱敏规则处理抽象方法
     *
     * @param fieldValue 待脱敏字段
     * @param desensitizeType 脱敏规则类型
     * @return String
     * @author jinjiayu
     */
    public abstract String doRule(String fieldValue, String desensitizeType);

    public AbstractDesensitizeWrapper<T,R> add(DesensitizeFunc<T,R> desensitizeFunc, String desensitizeType) {
        if (this.desensitizeFuncMap == null) {
            this.desensitizeFuncMap = new HashMap<>();
        }
        List<DesensitizeFunc<T,R>> desensitizeFuncList = this.desensitizeFuncMap.get(desensitizeType);
        if (desensitizeFuncList == null) {
            desensitizeFuncList = new ArrayList<>();
        }
        desensitizeFuncList.add(desensitizeFunc);
        this.desensitizeFuncMap.put(desensitizeType, desensitizeFuncList);

        return this;
    }

    /**
     * 动态脱敏处理
     * 1.获取desensitizeFuncWrapper对象中的desensitizeFuncMap,即待脱敏的字段列表,不同脱敏类型单独维护一个List
     * 2.遍历所有脱敏类型对应的List,按照脱敏类型进行字段脱敏处理,将脱敏后的数据赋给待脱敏对象,最终返回已经完成脱敏处理的对象
     *
     * @return T
     * @author jinjiayu
     */
    public T doDesensitize() {
        if (CollectionUtils.isEmpty(desensitizeFuncMap)) {
            return null;
        }

        for(String key : desensitizeFuncMap.keySet()){
            List<DesensitizeFunc<T, R>> desensitizeFuncs = desensitizeFuncMap.get(key);
            if (CollectionUtils.isEmpty(desensitizeFuncs)) {
                continue;
            }
            for (DesensitizeFunc<T, R> funcItem : desensitizeFuncs) {
                Field field = getField(funcItem);
                // 设置不检查字段访问权限
                field.setAccessible(true);
                try {
                    Object fieldValue = field.get(obj);
                    String fieldValueStr = fieldValue.toString();

                    // 根据不同进行相应的脱敏处理
                    fieldValueStr = doRule(fieldValueStr, key);

                    field.set(obj, fieldValueStr);

                } catch (Exception e) {
                    log.error("字段{}脱敏失败!错误信息:{}",field.getName(),e.getMessage());
                }
            }
        }

        return obj;
    }

    public static <T, R> List<Field> getFields(List<DesensitizeFunc<T, R>> functions) {
        List<Field> fields = new ArrayList<>();
        if (CollectionUtils.isEmpty(functions)){
            return fields;
        }
        for (DesensitizeFunc<T, R> item : functions) {
            Field field = getField(item);
            fields.add(field);
        }
        return fields;
    }

    public static <T,R> String getFieldName(DesensitizeFunc<T,R> function) {
        Field field = getField(function);
        return field.getName();
    }

    public static Field getField(DesensitizeFunc<?, ?> function) {
        return cache.computeIfAbsent(function, AbstractDesensitizeWrapper::findField);
    }

    public static Field findField(DesensitizeFunc<?, ?> function) {
        Field field = null;
        String fieldName = null;
        try {
            // 第1步 获取SerializedLambda
            Method method = function.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda) method.invoke(function);
            // 第2步 implMethodName 即为Field对应的Getter方法名
            String implMethodName = serializedLambda.getImplMethodName();
            if (implMethodName.startsWith("get") && implMethodName.length() > 3) {
                fieldName = Introspector.decapitalize(implMethodName.substring(3));

            } else if (implMethodName.startsWith("is") && implMethodName.length() > 2) {
                fieldName = Introspector.decapitalize(implMethodName.substring(2));
            } else if (implMethodName.startsWith("lambda$")) {
                throw new IllegalArgumentException("不能传递lambda表达式,只能使用方法引用");

            } else {
                throw new IllegalArgumentException(implMethodName + "不是Getter方法引用");
            }
            // 第3步 获取的Class是字符串，并且包名是“/”分割，需要替换成“.”，才能获取到对应的Class对象
            String declaredClass = serializedLambda.getImplClass().replace("/", ".");
            Class<?> aClass = Class.forName(declaredClass, false, ClassUtils.getDefaultClassLoader());

            // 第4步  Spring 中的反射工具类获取Class中定义的Field
            field = ReflectionUtils.findField(aClass, fieldName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 第5步 如果没有找到对应的字段应该抛出异常
        if (field != null) {
            return field;
        }
        throw new NoSuchFieldError(fieldName);
    }

    private AbstractDesensitizeWrapper() {}

    public AbstractDesensitizeWrapper(T obj) {
        if (obj == null) {
            throw new RuntimeException("对象不能为空!");
        }
        this.obj = obj;
    }

}